//回复函数
function setReplies(id){
	$("#m_replies").val("");//清空回复输入
	$("#MyReplies").modal("show"); //展示回复的模态框
    var username = null;
    $.get("getsession",function(data){
    	username=data.username;
    });
    var type=0;var tid=null;
	if(document.getElementById("right-top").innerHTML=="当前位置：有话要说"){
		type=1;
		tid="#tb";
	}
	else if(document.getElementById("right-top").innerHTML=="当前位置：办公报修"){
		type=2;
		tid="#office";
	}
	else if(document.getElementById("right-top").innerHTML=="当前位置：投诉平台"){
		type=3;
		tid="#ts";
	}
	$('#confirm_replies').unbind('click').bind('click',function(){
		var t = $("#m_replies").val();
		$.ajax({				
         type: "get",
         url: "../message/addReply",
         async: false,
         data: {"m_id": id,"r_details":$("#m_replies").val(),"username":username},       
         success: function (data) {        	 
        	 $("#MyReplies").modal("hide"); 
        	 alert("回复成功！");
            tableReload(tid,type);
         },
         error: function (data) {
        	 $("#m_replies").val("回复失败，请重试！");
         }
     });
	});
	$('#clear_replies').click(function(){
		$("#m_replies").val("");
	});	
}
//有话要说查询查询
function yhysquery(){	
		var yhysvalue = $("#yhysvalue").val();
		var start = $("#start1").val();
		var end = $("#end1").val()
		if(start==""){
			start = "2016-06-16 23:59:59";
		}
		if(end==""){
			end="2099-06-16 23:59:59";
		}
		var role=null;                    	
		$.get("getsession",function(data){   
			role=data.role;
			fuzzyQuery(1,yhysvalue,"#tb",role,start,end);
		});		
			
}
//有话要说查询清空
function yhysclear(){
	$("#yhysvalue").val("");	
}
//投诉模块查询
function tsquery(){	
	var tsvalue = $("#tsvalue").val();
	var start = $("#start2").val();
	var end = $("#end2").val();
	if(start==""){
		start = "2016-06-16 23:59:59";
	}
	if(end==""){
		end="2099-06-16 23:59:59";
	}
	var role=null;                    	
	$.get("getsession",function(data){   
		role=data.role;
		fuzzyQuery(3,tsvalue,"#ts",role,start,end);
	});
	
}
//投诉模块查询清空
function tsclear(){
	$("#tsvalue").val("");	
}
//报修模块查询
function bgquery(){	
	var bgvalue = $("#bgvalue").val();
	var start = $("#start").val();
	var end = $("#end").val();
	if(start==""){
		start = "2016-06-16 23:59:59";
	}
	if(end==""){
		end="2099-06-16 23:59:59";
	}
	var role=null;                    	
	$.get("getsession",function(data){   
		role=data.role;
		fuzzyQuery(2,bgvalue,"#office",role,start,end);
	});
	
}
//报修模块查询清空
function bgclear(){
	$("#bgvalue").val("");	
}
//用户管理查询清空
function yhglclear(){
	$("#yhglvalue").val("");	
}
//模糊查询，6个参数，type：消息类型;queryDate：输入的查询内容;id:需要匹配表的id,
//role：当前用户的角色,startTime:开始时间，endTime:结束时间
function fuzzyQuery(type,queryDate,id,role,startTime,endTime){
	$.ajax({				
        type: "post",
        url: "../message/indistincts",
        async: false,
        data: {"type": type,"indistinct":queryDate,"begin":startTime,"end":endTime},
        dataType: "json",
        success: function (data) {
        	$(id).dataTable().fnDestroy();//销毁当前表
        	$(id).dataTable({           //重绘表   	                                  
                bPaginate:true,//是否分页，默认为true  
                "iDisplayLength":10,//设置每页展示的行数
            	"bProcessing": false, // 是否显示取数据时的那个等待提示           
                "bSortable":true,
                "bScrollCollapse" : true,
                "bFilter":false,                 
                "bLengthChange":false,
                "bInfo":true,
                "fnDrawCallback"    : function(){
	             　　	this.api().column(1).nodes().each(function(cell, i) {
		             　　　　cell.innerHTML =  i + 1;
		             　　	});
                },
                "oLanguage": { //国际化配置  
                    "sProcessing" : "正在获取数据，请稍后...",    
                    "sLengthMenu" : "显示 _MENU_ 条",    
                    "sZeroRecords" : "没有您要搜索的内容",    
                    "sInfo" : "共 _TOTAL_ 条记录，当前显示_PAGE_页",    
                    "sInfoEmpty" : "记录数为0",    
                    "sInfoFiltered" : "(全部记录数 _MAX_ 条)",    
                    "sInfoPostFix" : "",    
                    "sSearch" : "搜索",    
                    "sUrl" : "",                    
                    "oPaginate": {    
                        "sFirst" : "第一页",    
                        "sPrevious" : "上一页",    
                        "sNext" : "下一页",    
                        "sLast" : "最后一页"    
                    }             		 
                },
               "data": data,             
                "columns": [
                	{ "data":"" },
	           		{ "data":null }, 
	           		{ "data": "m_time"},                    
	           		{ "data": "m_details" },
	   				{ "data": "status" }, 
	   				{
	                  "data":"m_id"
	   				}, 
	               { "data": "m_number","visible":false },
	               { "data": "type","visible":false },
	   				{ "data": "username","visible":false }, 
                ],
               
                columnDefs : [{  
                    targets : [0],  
                    orderable : false,  
                    render : function(id, type, row, meta) {  
                        return '<input id="input-' + id  
                                + '" type="checkbox" name="ids" value=' + id  
                                + '><label for="input-' + id + '"></label>';  
                    }  
                },
                {  
                    targets: [3],  
                    render: function(data, type, row, meta) { 
                    	var num = data.indexOf('。');
                    	if (num>26||(num==-1&&data.length>26)){
                    		return  data.substring(0,26);
                    	}
                    	else if(num<=26&&num!=-1){
                    		return data.substring(0,num);
                    	} 
                    	else{
                    		return data;
                    	}
                    }  
                },
                {  
                    targets: [4],  
                    render: function(data, type, row, meta) {                   	
                    	if (data==0){
                    		return  "新建";
                    	}
                    	else{
                    		return "完成";
                    	}                        
                    }  
                },
                {  
                	targets: [5],  
                    render: function(data, type, row, meta) { 
                    	                   		                    		
                    	if(role=="管理员"||role=="总经理"){
                            return'<img src="../image/02-lookup.png"><a '
                            +'title="details" href="javascript:;" onclick="getDetails('+data+')" '
    						+'style="text-decoration:none;margin-right:10px;">查看详情</a>'+'<span class="huifu"><img src="../image/02-answer.png"><a'
    		                   +'title="replies" href="javascript:;" onclick="setReplies('+data+')" '
    							+'style="text-decoration:none;">回复话题</a></span>'; 
                        		}
                        		else{
                        			   return '<img src="../image/02-lookup.png"><a '
                                       +'title="details" href="javascript:;" onclick="getDetails('+data+')" '
               						+'style="text-decoration:none;margin-right:10px;">查看详情</a>';
                        			}
                    } 
                }				
     		] ,                              
         }); 
        },
        error: function (data) {
       	 alert("查询失败，请重试！");
        }
    });
}

//新建话题并把话题存放到数据库的函数
//有话要说新建话题
function yhysTopic(){
	setNewTopic(1,"#tb");
}
//办公报修
function bgTopic(){
	setNewTopic(2,"#office");
}
//投诉平台
function tsTopic(){
	setNewTopic(3,"#ts");
}
//两个参数，id为表的id,type为数据类型
function setNewTopic(type,id){
	$("#new_content").val("");
	$('#addTopic').modal("show");
	$('#noneName').click(function(){
		if($('#noneName').attr("src")=="../image/02-newWindow-noneName.png"){
			$('#noneName').attr("src","../image/02-newWindow-realName.png");
			$('#getRealName').attr("src","../image/02-newWindow-noneName.png");
		} 
		else {
			$('#noneName').attr("src","../image/02-newWindow-noneName.png");
			$('#getRealName').attr("src","../image/02-newWindow-realName.png");
		}
	});
	$('#getRealName').click(function(){
		if($('#getRealName').attr("src")=="../image/02-newWindow-realName.png"){
			$('#noneName').attr("src","../image/02-newWindow-realName.png");
			$('#getRealName').attr("src","../image/02-newWindow-noneName.png");
		} 
		else{
			$('#noneName').attr("src","../image/02-newWindow-noneName.png");
			$('#getRealName').attr("src","../image/02-newWindow-realName.png");
		}
	});	
	
	$('#newbuild').unbind('click').bind('click',function(){
		var name = null;		
		var t = $("#new_content").val();
		$.get("getsession",function(data){
			if($('#getRealName').attr("src")=="../image/02-newWindow-noneName.png"){
				name="佚名";
			}
			else{
			name=data.realname;
			}
			$.ajax({				
		         type: "get",
		         url: "../message/addMessage",
		         async: false,
		         data: {"type":type,"username":name,"m_details":$("#new_content").val()},
		         //dataType: "json",
		         success: function (data) {        	
		        	 $("#addTopic").modal("hide"); 
		        	 alert("新建成功！");	
		        	 tableReload(id,type);
		         },
		         error: function (data) {
		        	 $("#new_content").val("新建失败，请重试！");
		         }
		     });    
	});
			
	});
}
//表格刷新，id为表的id,type为数据类型
function tableReload(id,type){
	var role=null;                    	
	$.get("getsession",function(data){   
		role=data.role;
	});
	 $(id).dataTable().fnDestroy();//销毁当前表
  	$(id).dataTable({           //重绘表   
  		
  		ajax: {
             url: "../message/lists",
             type:"post",
             data : { "type":type                    		  
             		}, 
             		 dataSrc: function(result) {
                          //这里result和上面jquery的ajax的代码类似，也是可以得到data.json的数据，但是这样的格式，Datatables不能直接使用，这时候需要在这里处理一下
                          //直接返回Datatables需要的那部分数据即可
                         return result.data;
             		 }
         },
          bPaginate:true,//是否分页，默认为true  
         "iDisplayLength":10,//设置每页展示的行数
      	"bProcessing": false, // 是否显示取数据时的那个等待提示           
          "bSortable":true,
          "bScrollCollapse" : true,
          "bFilter":false,                 
          "bLengthChange":false,
          "bInfo":true,
          "fnDrawCallback"    : function(){
           　　		this.api().column(1).nodes().each(function(cell, i) {
	             　　　　cell.innerHTML =  i + 1;
	             　　	});
          	},
          "oLanguage": { //国际化配置  
              "sProcessing" : "正在获取数据，请稍后...",    
              "sLengthMenu" : "显示 _MENU_ 条",    
              "sZeroRecords" : "没有您要搜索的内容",    
              "sInfo" : "共 _TOTAL_ 条记录，当前显示_PAGE_页",    
              "sInfoEmpty" : "记录数为0",    
              "sInfoFiltered" : "(全部记录数 _MAX_ 条)",    
              "sInfoPostFix" : "",    
              "sSearch" : "搜索",    
              "sUrl" : "",                    
              "oPaginate": {    
                  "sFirst" : "第一页",    
                  "sPrevious" : "上一页",    
                  "sNext" : "下一页",    
                  "sLast" : "最后一页"    
              }             		 
          },		                         
          "columns": [
        	  { "data":"" },
         		{ "data":null }, 
         		{ "data": "m_time"},                    
         		{ "data": "m_details" },
 				{ "data": "status" }, 
 				{
                "data":"m_id"
             }, 
             { "data": "m_number","visible":false },
             { "data": "type","visible":false },
 				{ "data": "username","visible":false }
          ],
         
          columnDefs : [{  
              targets : [0],  
              orderable : false,  
              render : function(id, type, row, meta) {  
                  return '<input id="input-' + id  
                          + '" type="checkbox" name="ids" value=' + id  
                          + '><label for="input-' + id + '"></label>';  
              }  
          },
          {  
              targets: [3],  
              render: function(data, type, row, meta) { 
              	var num = data.indexOf('。');
              	if (num>26||(num==-1&&data.length>26)){
              		return  data.substring(0,26);
              	}
              	else if(num<=26&&num!=-1){
              		return data.substring(0,num);
              	} 
              	else{
              		return data;
              	}
              }  
          },
          {  
              targets: [4],  
              render: function(data, type, row, meta) {                   	
              	if (data==0){
              		return  "新建";
              	}
              	else{
              		return "完成";
              	}                        
              }  
          },
          {  
         	 targets: [5],  
              render: function(data, type, row, meta) { 
              	                   		                    		
              	if(role=="管理员"||role=="总经理"){
                      return'<img src="../image/02-lookup.png"><a data-toggle="modal" data-target="#myModal" '
                      +'title="details" href="javascript:;" onclick="getDetails('+data+')" '
						+'style="text-decoration:none;margin-right:10px;">查看详情</a>'+'<span class="huifu"><img src="../image/02-answer.png"><a'
		                   +'title="replies" href="javascript:;" onclick="setReplies('+data+')" '
							+'style="text-decoration:none;">回复话题</a></span>'; 
                  		}
                  		else{
                  			   return '<img src="../image/02-lookup.png"><a data-toggle="modal" data-target="#myModal" '
                                 +'title="details" href="javascript:;" onclick="getDetails('+data+')" '
         						+'style="text-decoration:none;margin-right:10px;">查看详情</a>';
                  			}
              }
          }				
		] ,                              
   }); 
}
//从数据库获取话题详情的函数
function getDetails(id){
    	 //添加数据并将说去的数据返回
    	$.ajax({
            type: "get",
            url: "../message/details",
            async: false,
            data: {"m_id": id},
            dataType: "json",
            success: function (data) {
            	var jsonStr = JSON.stringify( data.replies );                	                	
            	var id=data.message.m_id;
            	var time=data.message.m_time;
            	var username=data.message.username;
            	var details=data.message.m_details;               	                	
            	var replies=data.replies;
            	var rname=new Array(data.replies.length);
            	var rtime=new Array(data.replies.length);
            	var rdetails=new Array(data.replies.length);
            	for(var i=0;i<data.replies.length;i++){
            		rname[i]=data.replies[i].username;
                	rtime[i] = data.replies[i].r_time;
                	rdetails[i]=data.replies[i].r_details;
            	}                	
            	$('#modal-details .m_username').text("发布者："+username);
            	$('#modal-details .m_time').text("发布时间："+time);
            	$('#modal-details .m_content').text("内容："+details); 
            	if(data.replies.length==0){
            		replies="暂无回复";
            		$('#modal-details .m_replies').text("回复："+replies);
            	}
            	else{
            		var r="";                	
            		for(var j=0;j<data.replies.length;j++){
            			r += "回复人："+rname[j]+"回复时间："+rtime[j]+
        				"回复内容："+rdetails[j]+"<br/>";               			
            		}                		
            		$('#modal-details .m_replies').html(r);
            	}                              	              	                 
            },
            error: function (data) {
            	$('#modal-details').text("加载详情失败，请重试！"+id);
            }
        });
     } 
//点击侧边栏图片实现侧边缩放
function sideBar(){
	var side = document.getElementById("sideBar");
	var oUl = document.getElementById("left-side");	
	var style = oUl.style;
	if(style.display=="none"){
		style.display="block";
		side.className="open";
		$(".key-content").css("margin-left","17%");
		$(".key-content").css("width","80.5%");
		$(".query-top-center").css("margin-left","17%");
		$(".query-top-center").css("width","80.5%");		
	}
	else{
		style.display="none";
		side.className="";
		$(".key-content").css("margin-left","2%");
		$(".key-content").css("width","96%");
		$(".query-top-center").css("margin-left","2%");
		$(".query-top-center").css("width","96%");		
	}	
}
//点击设置弹出模态框可修改基本信息
function changeInfo(){
	$("#myModalLabel").text("修改");
	$.get("getsession",function(data){
		var name = data.username;
		var role = data.role;
    $("#username").val(data.username);
    $("#name").val(data.realname);
    $("#password").val(data.password);
    $("#department").val(data.department);
    $("#role").val(data.role); 	
	$('#changeInfo').modal("show");
	$('#save').unbind('click').bind('click',function(){
		$.ajax({
	        url:"../user/update",
	        data: {
	            "username": name,
	            "realname": $("#name").val(),
	            "password": $("#password").val(),
	            "department": $("#department").val(),
	            "role": role,        
	        }, success: function (result) {
	        	alert("修改信息成功！");
	            $("#changeInfo").modal("hide"); 
	            window.location.href = "../login.html";
	        	}      
	    	});
		});
	});
}
//点击弹出增加单个用户的窗口
function addUser(){
	$("#addUser").modal("show");
	$('#add-confirm').unbind('click').bind('click',function(){
		$.ajax({
	        url:"../user/addUser",
	        type:"post",
	        data: {
	            "username": $("#addusername").val(),
	            "realname": $("#addname").val(),
	            "password": $("#addpassword").val(),
	            "department": $("#adddepartment").val(),
	            "role": $("#addrole").val(),        
	        }, success: function (result) {
	        	alert("新增用户成功！");
	            $("#addUser").modal("hide"); 	           
	        }      
	    });
	});
}
